<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class LinkController extends Controller
{

	//index

    //add
    public function add()
    {
    	$title = '链接添加';
    	return view('admin.link.add',['title' => $title]);
    }

    //insert
    public function insert(Request $request)
    {
      $data = $request -> except(['_token']);
      
      if($request -> hasFile('img_head'))
        {
            if($request -> file('img_head') -> isValid())
            {
                //移动文件
                $suffix = $request -> file('img_head') -> getClientOriginalExtension();
                //随机一个文件名
                $filename = time().mt_rand(100000,9999999);

                //移动文件
                $request -> file('img_head') -> move('./uploads', $filename.'.'.$suffix);
                $data['img_head'] = $filename.'.'.$suffix;
            }

        }

    	

    	// $data['token'] = str_random(50);

    	// dd($data);
    	$res = DB::table('link') -> insert($data);
    	if($res)
  		{
  			return redirect('/admin/link/index');
  		}else
  		{
  			return back();
  		}

  		
    }
   

    public function index(Request $request)
	{

      $data = DB::table('link')
       -> where(function($query) use($request){
        $query -> where('name','like','%'.$request -> input('keywords').'%');
       })
       -> paginate($request -> input('num',10));
       // dd($data);
      $title = '链接列表';

      return view('admin.link.index',['title' => $title,'data' => $data,'request'=>$request -> all()]);
		
	}

	public function edit($id)
	{
		$data = DB::table('link') -> where('id',$id) -> first();
    	$title = '用户编辑';
    	return view('admin.link.edit',['title' => $title,'data' => $data]);  
	}

	public function update(Request $request)
	{
		$data = $request -> except('_token','id'); 
    	$id = $request -> input('id');
    	$res = DB::table('link') ->where('id',$id) -> update($data);
  		if($res)
  		{
  			return redirect('/admin/link/index') -> with(['info' => '更新成功']);
  		}else
  		{
  			return back();
  		}
	}

	public function delete($id)
	{
		$res = DB::table('link') -> where('id',$id) -> delete();

		if($res)
  		{
  			return redirect('/admin/link/index') -> with(['info' => '删除成功']);
  		}else
  		{
  			return redirect('/admin/link/index') -> with(['info' => '删除不成功']);
  		}
	}
}
